package name.jautzy.esi.client;

import name.jautzy.esi.client.model.EsiComment;
import name.jautzy.esi.client.model.EsiShip;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.google.gwt.user.client.rpc.AsyncCallback;


public class AddCommentListener extends SelectionListener<ButtonEvent> {
	private ListStore<EsiComment> sStore;
	String fitId;
	
	public AddCommentListener (ListStore<EsiComment> sStore, String fitId) {
		super();
		this.sStore = sStore;
		this.fitId = fitId;
	}
	
	@Override
	public void componentSelected(ButtonEvent ce) {  

        final Window formWindow = new Window();
        formWindow.setSize(600,450);
        formWindow.setPlain(false);
        formWindow.setModal(true);
        formWindow.setHeading("New Comment");
        formWindow.setLayout(new FormLayout());

        final TextArea area = new TextArea();
        area.setFieldLabel("Comment");
        area.setName("comment");
        area.setAllowBlank(false);
        
        FormData data = new FormData (450,300);
        formWindow.add(area,data);

        final Button btn = new Button("OK");  
        btn.addSelectionListener(new SelectionListener<ButtonEvent>() {  
      
        	@Override  
        	public void componentSelected(ButtonEvent ce) {  
        	
        			AsyncCallback<EsiComment> callback = new AsyncCallback<EsiComment>() {
    	        	    public void onSuccess(EsiComment result) {
    	        	    	if (result != null) {
    	        	    		sStore.add(result);
    	        	    		sStore.commitChanges();
    	        	    		Esi.getEsi().addMessage("comment added");
    	        	    	}
    	        	    	else
    	        	    		Esi.getEsi().addMessage("Can't add comment"); 
    	        	    	
    	        	    }

    	        	    public void onFailure(Throwable caught) {
    	        	    	Esi.getEsi().addMessage("Can't add comment : "+caught.toString()); 
    	        	    	
    	        	    }
    	        	  };

    	        	Esi.getEsi().getLoginService().addComment(fitId, area.getValue(),callback); 
    	        	formWindow.hide();
        		}  
   
        });  
        formWindow.addButton(btn);  
        formWindow.show();
	}
}
